import json
from datetime import datetime
from MY_SM import my_sm4

import requests

class FangTu():
    def __init__(self, appId, secret, ip):
        self.appId = appId
        self.secret = secret
        self.ip = ip
        self.token_url = f'{self.ip}/token?clientId={self.appId}&grantType=client_credentials'
        self.sm4 = my_sm4.SM4()

    def _encrypt(self,plain_text):
        cipher_text = self.sm4.encryptSM4_StrtoBase64(self.secret, plain_text)
        return cipher_text

    def _decrypt(self,cipher_text):
        decrypt_text = self.sm4.decryptSM4_Base64toStr(self.secret, cipher_text)
        return decrypt_text
    def __get_token_authorization(self):
        timestamp = str(int(datetime.now().timestamp() * 1000))
        plain_text = f'{self.appId}:{timestamp}'
        cipher_text = self._encrypt(plain_text)
        return cipher_text

    def __get_token(self):
        headers = {}
        headers['Authorization'] = self.__get_token_authorization()
        result = requests.post(url=self.token_url, headers=headers)
        return result.json()['accessToken']

    def getResponse(self, url, param):
        headers = {}
        headers['Content-Type'] = 'application/json'
        headers['Authorization'] = f'Bearer {self.__get_token()}'
        json_data = json.dumps(param)
        encrypt_param = self._encrypt(json_data)
        res_url = f'{self.ip}{url}'
        res = requests.post(url=res_url, headers=headers,data=encrypt_param)
        result = self._decrypt(res.text)
        return result

